<template>
    <view class="container" :style="themeColor">
        <view class="header">
            <view class="content">
                <view class="title">{{ infoData.Title }}</view>
                <view class="row">活动时间：{{ StartTime }} - {{ EndTime }}</view>
                <view class="row">套餐类型：{{ infoData.PackageMode == 1 ? '配套' : '配比' }}下单</view>
                <view class="row" v-if="infoData.PackageMode == 1">套餐说明：需A组下单{{ infoData.BaseGoodsAmount }}， B组下单{{
                    infoData.AddGoodsAmount }}<text v-show="infoData.BuyAmount != 0">, 合并{{
                        infoData.BuyAmount }}配套起下单</text>
                </view>
                <view class="row" v-else>套餐说明：需A组下单配比{{ infoData.BaseGoodsAmount }}， B组下单配比{{ infoData.AddGoodsAmount
                }}
                </view>
            </view>
        </view>
        <view class="header2">
            <view class="btn-box">
                <text class="djstxt1 mr-10">距离{{ infoData.SaleStateName == "进行中" ? "结束" : "开始" }}</text>
                <text class="css-djs">{{ Days }}</text>
                <text class="djstxt1">天</text>
                <text class="css-djs">{{ Hours }}</text>
                <text class="djstxt1">:</text>
                <text class="css-djs">{{ Minutes }}</text>
                <text class="djstxt1">:</text>
                <text class="css-djs">{{ Seconds }}</text>
            </view>
        </view>

        <!-- 组合详情 -->
        <view class="main">
            <view class="product-main-list" :style="{ height: listHeight }">
                <!-- A组套餐 -->
                <view class="product-main-item">
                    <view class="item-title">
                        <view class="name">A组套餐</view>
                        <view class="tip" v-if="infoData.PackageMode == 1">需下单合并数量<text>{{ infoData.BaseGoodsAmount
                        }}</text></view>
                        <view class="tip" v-else>下单配比<text>{{ infoData.BaseGoodsAmount }}</text></view>
                    </view>
                    <view class="item-main" v-for="(item, index) in infoData.ProductList" :key="index">
                        <image class="item-img" mode="aspectFill" :src="easyGetImgUrl(item.ProductImage)"></image>
                        <view class="item-con">
                            <view class="name">{{ item.ProductName }}</view>
                            <view class="spec" v-if="item.Attribute">规格：{{ item.Attribute }}</view>
                            <view class="stock">库存：{{ item.ActStock }}</view>
                            <view class="rule">{{ item.Amount }}{{ item.UnitName }}起订，限购{{ item.LimitAmount }}{{
                                item.UnitName }}</view>
                            <view class="handler">
                                <view class="price">
                                    <text>¥{{ item.SalePrice }}</text>/{{ item.UnitName }}
                                </view>
                                <view class="input-number-box">
                                    <button class="number-btn number-btn-minus"
                                        :class="item.amount <= 0 ? 'color-shadow' : ''"
                                        @click="upNum(item, -1)"></button>
                                    <view class="btn-input-box"
                                        :class="item.amount.toString().length > 6 ? 'text-show-line-1' : ''"
                                        @click="showpop">
                                        {{ item.amount }}
                                    </view>
                                    <button class="number-btn number-btn-plus" @click="upNum(item, 1)"></button>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="describe" v-if="infoData.PackageMode == 1">
                        <uni-icons type="info-filled" size="30" color="#FF6A42"
                            style="margin-right: 6rpx;"></uni-icons>A组商品需合并下单数量{{ infoData.BaseGoodsAmount
                            }}，现已下单{{ BaseGoodsAmount }}，需再下单{{ BaseGoodsAmount > infoData.BaseGoodsAmount ? 0 :
                            infoData.BaseGoodsAmount - BaseGoodsAmount }}
                    </view>
                </view>

                <!-- B组套餐 -->
                <view class="product-main-item">
                    <view class="item-title">
                        <view class="name">B组套餐</view>
                        <view class="tip" v-if="infoData.PackageMode == 1">需下单合并数量<text>{{ infoData.AddGoodsAmount
                        }}</text></view>
                        <view class="tip" v-else>下单配比<text>{{ infoData.AddGoodsAmount }}</text></view>
                    </view>
                    <view class="item-main" v-for="(item, index) in infoData.OptionalProductList" :key="index">
                        <image class="item-img" mode="aspectFill" :src="easyGetImgUrl(item.ProductImage)"></image>
                        <view class="item-con">
                            <view class="name">{{ item.ProductName }}</view>
                            <view class="spec" v-if="item.Attribute">规格：{{ item.Attribute }}</view>
                            <view class="stock">库存：{{ item.ActStock }}</view>
                            <view class="rule">{{ item.Amount }}{{ item.UnitName }}起订，限购{{ item.LimitAmount }}{{
                                item.UnitName }}</view>
                            <view class="handler">
                                <view class="price">
                                    <text>¥{{ item.SalePrice }}</text>/{{ item.UnitName }}
                                </view>
                                <view class="input-number-box">
                                    <button class="number-btn number-btn-minus"
                                        :class="item.amount <= 0 ? 'color-shadow' : ''"
                                        @click="upNum(item, -1)"></button>
                                    <view class="btn-input-box"
                                        :class="item.amount.toString().length > 6 ? 'text-show-line-1' : ''"
                                        @click="showpop">
                                        {{ item.amount }}
                                    </view>
                                    <button class="number-btn number-btn-plus" @click="upNum(item, 1)"></button>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="describe" v-if="infoData.PackageMode == 1">
                        <uni-icons type="info-filled" size="30" color="#FF6A42"
                            style="margin-right: 6rpx;"></uni-icons>B组商品需合并下单数量{{ infoData.AddGoodsAmount
                            }}，现已下单{{ AddGoodsAmount }}, 需再下单{{ AddGoodsAmount > infoData.AddGoodsAmount ? 0 :
                            infoData.AddGoodsAmount - AddGoodsAmount }}
                    </view>
                </view>
            </view>
        </view>

        <!-- 底部 -->
        <view class="bottom-bar policy-bottom-bar">
            <view class="total">
                <view style="font-size: 24rpx; color:#FF3100;">已选A组数量{{ BaseGoodsAmount }}，B组数量{{ AddGoodsAmount }}
                </view>
                <view class="price">套餐价：<text>{{ totalPrice }}</text></view>
            </view>
            <button class="btn btn-success btn-submitOrder" :class="{ disable: btnDisabled }" :disabled="btnDisabled"
                @click="submitOrder">
                在线下单
            </button>
        </view>
    </view>
</template>

<script>
import { GetNowTime } from "@/service/api/activity.js"
import { GetPackageBuy } from "@/service/api/packageBuy.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import utilsOld from "@/utils/utilsOld.js"
import { getUserCarList, AddOrUpdateTempAmount } from "@/service/api/member.js"
export default {
    components: {
    },
    data() {
        return {
            isloadding: false,
            datas: [],
            requestData: {
                pageIndex: 1,
                pageSize: 10,
            },
            listHeight: 0,
            id: "",
            Days: "00",
            Hours: "00",
            Minutes: "00",
            Seconds: "00",
            infoData: {},
            nowTime: null,
            StartTime: null,
            EndTime: null,
            BaseGoodsAmount: 0, // a组实际下单数量
            AddGoodsAmount: 0, // b组实际下单数量
            totalPrice: 0, // 总价
            btnDisabled: true
        }
    },
    onLoad(e) {
        this.id = e.id
        this.getSalesInfo()
    },
    mounted() {
        this.getListHeight()
    },
    methods: {
        getSalesInfo() {
            let path = "?id=" + this.id
            GetPackageBuy(path).then((res) => {
                if (res.State == 1) {
                    this.infoData = res.Data;
                    this.totalPrice = 0;
                    this.BaseGoodsAmount = 0;
                    this.AddGoodsAmount = 0;
                    if (this.infoData.ProductList?.length) {
                        this.infoData.ProductList.forEach(item => {
                            item.amount = item.Amount;
                            this.BaseGoodsAmount += item.amount
                            this.totalPrice += Number(item.amount) * Number(item.SalePrice);
                        });
                    }
                    if (this.infoData.OptionalProductList?.length) {
                        this.infoData.OptionalProductList.forEach(item => {
                            item.amount = item.Amount;
                            this.AddGoodsAmount += item.amount
                            this.totalPrice += Number(item.amount) * Number(item.SalePrice);
                        });
                    }
                    this.checkRule();
                    this.totalPrice = this.totalPrice.toFixed(2);
                    this.StartTime = utilsOld.dateFomat("yyyy-mm-dd", new Date(this.infoData.StartTime))
                    this.EndTime = utilsOld.dateFomat("yyyy-mm-dd", new Date(this.infoData.EndTime))
                    this.setInterval()
                }
            })
        },
        //数量变更
        upNum(item, type) {
            let amount = item.amount
            let addNum = 1; //默认加1
            if (type == 0) {
                let newNum = amount
                if (newNum >= item.ActStock && !this.getAppSet().NoCheckStock) {
                    let stockMaxNum = item.ActStock - (item.ActStock % addNum)
                    amount = stockMaxNum
                    this.easyToast("已是最大库存")
                } else {
                    amount = newNum
                }
                if (amount < 0) {
                    amount = 0
                }
            } else {
                amount = amount + type * addNum
            }
            if (amount < 0) {
                amount = 0
            }
            let LimitBuy = item.LimitAmount;
            if (LimitBuy > 0) {
                //限购
                if (amount > LimitBuy) {
                    this.easyToast("已达到限购数量")
                    return
                }
            }
            let Amount = item.Amount;
            if (Amount > 0 && amount < Amount) {
                amount = Amount
            }
            item.amount = amount;
            this.totalPrice = 0;
            this.BaseGoodsAmount = 0;
            this.infoData.ProductList.forEach(item => {
                this.BaseGoodsAmount += item.amount
                this.totalPrice += Number(item.amount) * Number(item.SalePrice);
            });
            this.AddGoodsAmount = 0;
            this.infoData.OptionalProductList.forEach(item => {
                this.AddGoodsAmount += item.amount
                this.totalPrice += Number(item.amount) * Number(item.SalePrice);
            });
            this.totalPrice = this.totalPrice.toFixed(2);
            this.checkRule()
        },
        // 校验配比规则
        checkRule() {
            this.btnDisabled = false;
            for (let item of this.infoData.ProductList) {
                // 判断必填商品
                if (item.Amount > 0 && item.amount < item.Amount) {
                    this.btnDisabled = true
                    return
                }
                this.btnDisabled = false
            }

            for (let item of this.infoData.OptionalProductList) {
                // 判断必填商品
                if (item.Amount > 0 && item.amount < item.Amount) {
                    this.btnDisabled = true
                    return
                }
                this.btnDisabled = false
            }

            let flag = (Number(this.BaseGoodsAmount ?? 0) + Number(this.AddGoodsAmount ?? 0)) >= this.infoData.BuyAmount ?? 0;
            if (this.infoData.BuyAmount == 0) { // 为不限制总数规则
                flag = true
            }
            if (this.infoData.PackageMode == 1) {
                // 配套时校验
                if ((this.BaseGoodsAmount < this.infoData.BaseGoodsAmount || this.AddGoodsAmount < this.infoData.AddGoodsAmount)) {
                    this.btnDisabled = true
                    return
                } else {
                    if (!flag) {
                        this.btnDisabled = true
                        return
                    }
                }
                this.btnDisabled = false
            } else {
                // 配比时校验
                let ratio1 = Number(this.infoData.BaseGoodsAmount) / Number(this.infoData.AddGoodsAmount); // 配比规则
                let ratio2 = Number(this.BaseGoodsAmount) / Number(this.AddGoodsAmount); // 实际配比
                if (!(ratio1 == ratio2 && this.BaseGoodsAmount >= this.infoData.BaseGoodsAmount && this.AddGoodsAmount >= this.infoData.AddGoodsAmount)) {
                    this.btnDisabled = true
                    return
                } else {
                    if (!flag) {
                        this.btnDisabled = true
                        return
                    }
                }
                this.btnDisabled = false
            }
        },
        // 在线下单
        submitOrder() {
            let datas = [];
            for (let item of this.infoData.ProductList) {
                // 判断必填商品
                if (item.Amount > 0 && item.amount < item.Amount) {
                    let errorTip = item.ProductName + "数量不能小于" + item.Amount;
                    this.easyToast(errorTip)
                    return
                }
                datas.push(
                    {
                        "unitId": item.UnitId,
                        "unitName": item.UnitName,
                        "productId": item.ProductId,
                        "skuId": item.SkuId,
                        "amount": item.amount,
                        "packageBuyId": item.ID
                    }
                )
            }

            for (let item of this.infoData.OptionalProductList) {
                // 判断必填商品
                if (item.Amount > 0 && item.amount < item.Amount) {
                    let errorTip = item.ProductName + "数量不能小于" + item.Amount;
                    this.easyToast(errorTip)
                    return
                }
                datas.push(
                    {
                        "unitId": item.UnitId,
                        "unitName": item.UnitName,
                        "productId": item.ProductId,
                        "skuId": item.SkuId,
                        "amount": item.amount,
                        "packageBuyId": item.ID
                    }
                )
            }

            let flag = (Number(this.BaseGoodsAmount ?? 0) + Number(this.AddGoodsAmount ?? 0)) >= this.infoData.BuyAmount ?? 0;
            if (this.infoData.BuyAmount == 0) { // 为不限制总数规则
                flag = true
            }
            if (this.infoData.PackageMode == 1) {
                // 配套时校验
                if (this.BaseGoodsAmount < this.infoData.BaseGoodsAmount || this.AddGoodsAmount < this.infoData.AddGoodsAmount) {
                    this.easyToast("请根据配套规则选择商品")
                    return
                } else {
                    if (!flag) {
                        this.easyToast("请根据配套规则选择商品")
                        return
                    }
                }
            } else {
                // 配比时校验
                let ratio1 = Number(this.infoData.BaseGoodsAmount) / Number(this.infoData.AddGoodsAmount); // 配比规则
                let ratio2 = Number(this.BaseGoodsAmount) / Number(this.AddGoodsAmount); // 实际配比
                if (!(ratio1 == ratio2 && this.BaseGoodsAmount >= this.infoData.BaseGoodsAmount && this.AddGoodsAmount >= this.infoData.AddGoodsAmount)) {
                    this.easyToast("请根据配比规则选择商品")
                    return
                } else {
                    if (!flag) {
                        this.easyToast("请根据配比规则选择商品")
                        return
                    }
                }
            }


            let path = "?orderType=15";
            AddOrUpdateTempAmount(datas, path).then((res) => {
                let param = {
                    isTempCar: true,
                    orderType: 15
                }
                getUserCarList(param).then((resp) => {
                    let ids = []
                    resp.Data.forEach((item) => {
                        ids.push(item.ID)
                    })
                    this.easyGoTo(
                        "/pages_shop/packet/order/submitOrder?ids=" +
                        ids.join(",") +
                        "&isTempCar=1" +
                        "&orderType=15" +
                        "&PackageBuyId=" + this.id
                    )
                })
            })
        },
        setInterval() {
            var that = this
            //当前时间
            GetNowTime().then((rsp) => {
                if (rsp.State == 1) {
                    that.nowTime = new Date(rsp.Data.replace(/-/g, "/")).getTime()
                    setInterval((e) => {
                        that.nowTime += 1000
                        that.setCountDown()
                    }, 1000)
                }
            })
        },
        //秒杀设置倒计时
        setCountDown() {
            if (!this.nowTime) {
                return
            }
            var diff = new Date(this.infoData.EndTime.replace(/-/g, "/")).getTime() - this.nowTime //时间差的毫秒数
            if (diff < 0) {
                diff = new Date(this.infoData.EndTime.replace(/-/g, "/")).getTime() - this.nowTime //时间差的毫秒数
            }
            if (diff >= 0) {
                //计算出相差天数
                var days = Math.floor(diff / (24 * 3600 * 1000))
                //计算出小时数
                var leave1 = diff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
                var hours = Math.floor(leave1 / (3600 * 1000))
                //计算相差分钟数
                var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
                var minutes = Math.floor(leave2 / (60 * 1000))
                //计算相差秒数
                var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
                var seconds = Math.round(leave3 / 1000)
                // item.CountDown = {
                //     Days: (days > 9 ? "" : "0") + days,
                //     Hours: (hours > 9 ? "" : "0") + hours,
                //     Minutes: (minutes > 9 ? "" : "0") + minutes,
                //     Seconds: (seconds > 9 ? "" : "0") + seconds
                // };
                this.Days = (days > 9 ? "" : "0") + days
                this.Hours = (hours > 9 ? "" : "0") + hours
                this.Minutes = (minutes > 9 ? "" : "0") + minutes
                this.Seconds = (seconds > 9 ? "" : "0") + seconds
            } else {
                // this.CountDown = {
                //     Days: "00",
                //     Hours: "00",
                //     Minutes: "00",
                //     Seconds: "00"
                // };
                this.Days = "00"
                this.Hours = "00"
                this.Minutes = "00"
                this.Seconds = "00"
            }
            this.$forceUpdate()
        },
        getListHeight(element) {
            setTimeout(e => {
                getElementHeight(this, ".product-main-list", (e) => {
                    //再获取列表高度
                    this.listHeight = e - uni.upx2px(120) + "px"
                    this.isloadding = true
                })
            }, 500)

        },
    },
}
</script>

<style lang="scss">
.container {}

.header {
    padding: 24rpx;
    height: 210rpx;
    background-color: $app-color-main;
    font-size: 24rpx;

    .content {
        background-color: #ffffff;
        border-radius: 32rpx;
        padding: 24rpx 44rpx;
        height: 210rpx;

        .title {
            font-size: 34rpx;
            font-weight: bold;
            padding-bottom: 16rpx;
        }

        .row {
            padding-bottom: 12rpx;
        }
    }
}

.header2 {
    margin: 30rpx auto;

    .btn-box {
        display: flex;
        flex-direction: row;
        justify-content: center;
        padding-top: 35rpx;

        .djstxt1 {
            color: $color-orange-1;
            font-size: 24rpx;
            font-weight: Medium;
        }

        .mr-10 {
            margin-right: 10rpx;
        }

        .css-djs {
            background-color: $color-orange-1;
            color: #ffffff;
            font-size: 28rpx;
            font-weight: bold;
            border-radius: 8rpx;
            padding: 5rpx 10rpx;
            margin-left: 5rpx;
            margin-right: 5rpx;
            margin-top: -5rpx;
        }
    }
}

.main {
    .product-main-list {
        overflow-y: scroll;
        margin: 0 24rpx;

        .product-main-item {
            padding: $app-page-padding;
            background: white;
            border-radius: 40rpx;
            margin-bottom: 24rpx;

            .item-title {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .name {
                    font-size: 34rpx;
                    font-weight: bold;
                }

                .tip {
                    background-color: rgba(0, 110, 255, .1);
                    padding: 4rpx 10rpx;
                    border-radius: 10rpx;
                    font-size: 22rpx;

                    text {
                        font-size: 30rpx;
                        font-weight: bold;
                        color: $color-blue
                    }
                }
            }

            .describe {
                display: flex;
                align-items: center;
                background-color: rgba(252, 242, 240, 1);
                color: $color-orange-1;
                font-size: 24rpx;
                padding: 14rpx;
            }

            .item-main {
                display: flex;
                border-bottom: #F0F0F0 solid 1px;
                padding: 24rpx 0;
            }

            .item-img {
                width: 120rpx;
                height: 120rpx;
                text-align: center;
                margin-right: 20rpx;
                border-radius: 8rpx;
                flex-shrink: 0;
            }

            .item-con {
                flex: 1;
                margin-left: 20rpx;

                .name {
                    font-size: 28rpx;
                    font-weight: bold;
                    padding-bottom: 12rpx;
                }

                .spec {
                    font-size: 24rpx;
                    padding-bottom: 6rpx;
                }

                .stock {
                    font-size: 24rpx;
                    padding-bottom: 6rpx;
                }

                .rule {
                    font-size: 24rpx;
                    padding-bottom: 6rpx;
                }

                .handler {
                    display: flex;
                    align-items: center;

                    .price {
                        flex: 1;
                        font-size: 24rpx;

                        text {
                            color: $color-orange-1;
                            font-size: 36rpx;
                            font-weight: bold;
                        }
                    }
                }
            }
        }
    }
}

.input-number-box {
    .btn-input-box {
        display: block;
        text-align: center;
        font-size: $font-size-26;
        height: auto;
        padding: 10rpx 0;
    }

    .number-btn {
        display: flex;
        justify-content: center;
        border: none;
        background-color: none;
        justify-content: center;
        align-items: center;
        position: relative;
        font-size: 45rpx;
        line-height: 56rpx;
        height: 56rpx;
        width: 56rpx;
        text-align: center;
        overflow: hidden;
        border-radius: 100rpx;
        display: block;
        background-repeat: no-repeat;
        background-size: 100%;
        background-position: center;

        &:before {
            border: none;
        }

        &:after {
            border: none;
        }
    }

    .number-btn-minus {
        background-image: url(@/static/icon/icon_btn_minus.png);
    }

    .number-btn-plus {
        background-image: url(@/static/icon/icon_btn_plus.png);
    }
}

.policy-bottom-bar {
    justify-content: space-between;

    .total {
        flex: 1;

        .price {
            font-size: 26rpx;

            text {
                font-size: 40rpx;
                font-weight: bold;
                color: $color-orange-1;
            }
        }
    }

    .btn-submitOrder {
        width: 220rpx;
        height: 80rpx;
        border-radius: 45rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32rpx;
        color: #ffffff;
    }

    .disable {
        color: $color-gray-3;
    }
}
</style>
